<template>
	<view>
		<view class="tabBox">
			<scroll-view scroll-x="true" :scroll-left="scrollLeft" :scroll-with-animation="true" class="scrollBox">
				<view class="box">
					<view class="tabItem" v-for="(item,index) in monthList" :key="index"
						:class="{'ac':tabCurrent == index}" @click="tabChange(item,index)">
						{{item}}
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				itemWidth: 0, //每个item的宽度
				scrollLeft: 0, //滑动距离
				tabCurrent: 0, //默认当前月份
				sendMonth: '',
				monthList: [{}]
			}
		},
		mounted() {
			let date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();
			let currentDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
			this.getMonthsInRange('2020-01-01', currentDate);

			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.tabItem').boundingClientRect(data => {
					this.itemWidth = data.width;
					this.scrollLeft = this.itemWidth * (this.tabCurrent - 1);
				}).exec();
			})
		},
		methods: {
			tabChange(item, index) {
				this.tabCurrent = index;
				this.sendMonth = item
				this.scrollLeft = this.itemWidth * (index - 1);
				this.$emit('tabChange', this.sendMonth)
			},
			getMonthsInRange(start, end) {
				var startMonth = new Date(start).getMonth();
				var endMonth = new Date(end).getMonth();
				var startYear = new Date(start).getFullYear();
				var endYear = new Date(end).getFullYear();
				var months = [];

				for (var i = startYear; i <= endYear; i++) {
					var monthStart = i === startYear ? startMonth : 0;
					var monthEnd = i === endYear ? endMonth : 11;

					for (var j = monthStart; j <= monthEnd; j++) {
						var month = j + 1;
						months.push(i + '-' + (month < 10 ? '0' + month : month));
					}
				}
				this.monthList = months
				this.tabCurrent = this.monthList.length - 1 // 初次加载默认显示
			}
		}
	}
</script>
<style lang="scss">
	.tabBox {
		background: #ffffff;
	}
	.scrollBox {
		margin: 0 24rpx;
		width: 700rpx;
	}

	/* 隐藏滚动条样式 */
	::-webkit-scrollbar {
		width: 0;
		height: 0;
	}

	.box {
		// width: 1400rpx;
		display: flex;
		align-items: center;
		height: 90rpx;
	}
	.tabItem {
		flex-shrink: 0;
		text-align: center;
		width: 140rpx;
		height: 60rpx;
		line-height: 60rpx;
		color: #636363;
		font-size: 28rpx;
		border-radius: 50rpx;
	}

	.ac {
		background: #F9682A;
		font-size: 28rpx;
		color: #FFFFFF;
	}
		
	
</style>
